package cn.ug.operation.service.impl;

import cn.ug.operation.bean.CupGuessUserBean;
import cn.ug.operation.bean.GameBean;
import cn.ug.operation.bean.GameStatisticsBean;
import cn.ug.operation.mapper.CupBallGameMapper;
import cn.ug.operation.mapper.CupGuessUserMapper;
import cn.ug.operation.mapper.entity.CupBallGame;
import cn.ug.operation.mapper.entity.CupGuessUser;
import cn.ug.operation.service.CupBallGameService;
import cn.ug.util.RedisConstantUtil;
import cn.ug.util.UF;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import static cn.ug.util.ConstantUtil.COLON;
import static cn.ug.util.ConstantUtil.NORMAL_DATE_FORMAT;

@Service
public class CupBallGameServiceImpl implements CupBallGameService {
    @Autowired
    private CupBallGameMapper cupBallGameMapper;
    @Autowired
    private CupGuessUserMapper cupGuessUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public GameStatisticsBean statisticsGame() {
        GameStatisticsBean bean = new GameStatisticsBean();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("startDate", "2018-05-01");
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        params.put("endDate", format.format(Calendar.getInstance().getTime()));
        List<CupBallGame> games = cupBallGameMapper.query(params);
        if (games != null) {
            int totalGoals = 0;
            int groupGoals = 0;
            for (CupBallGame game : games) {
                if (StringUtils.isNotBlank(game.getResult())) {
                    String[] infos = StringUtils.split(game.getResult(), COLON);
                    if (infos != null && infos.length == 2) {
                        try {
                            totalGoals += Integer.parseInt(infos[0]);
                            totalGoals += Integer.parseInt(infos[1]);
                            if (game.getType() == 1) {
                                groupGoals += Integer.parseInt(infos[0]);
                                groupGoals += Integer.parseInt(infos[1]);
                            }
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
            }
            bean.setTotalGoals(totalGoals);
            bean.setGroupGoals(groupGoals);
            bean.setTotalGuessNum(cupGuessUserMapper.countGuessedNum(0));
            bean.setGroupGuessNum(cupGuessUserMapper.countGuessedNum(1));
        }
        return bean;
    }

    @Override
    public int getTotalGold() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("startDate", "2018-05-01");
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        params.put("endDate", format.format(Calendar.getInstance().getTime()));
        List<CupBallGame> games = cupBallGameMapper.query(params);
        int totalGoals = 0;
        if (games != null) {
            for (CupBallGame game : games) {
                if (StringUtils.isNotBlank(game.getResult())) {
                    String[] infos = StringUtils.split(game.getResult(), COLON);
                    if (infos != null && infos.length == 2) {
                        try {
                            totalGoals += Integer.parseInt(infos[0]);
                            totalGoals += Integer.parseInt(infos[1]);
                        } catch (Exception e) {
                            continue;
                        }
                    }
                }
            }
        }
        return totalGoals + 171;
    }

    @Override
    public List<GameBean> listGames(String memberId) {
        if (StringUtils.isNotBlank(memberId)) {
            List<GameBean> games = cupBallGameMapper.queryAllForList();
            List<CupGuessUser> guessGames = cupGuessUserMapper.findByMemberId(memberId);
            if (games != null && games.size() > 0) {
                for (GameBean game : games) {
                    if (guessGames != null) {
                        for (CupGuessUser guessGame : guessGames) {
                            if (StringUtils.equals(game.getId(), guessGame.getGameId())) {
                                game.setGuessResult(guessGame.getGuessResult());
                                game.setGuessStatus(guessGame.getGuessStatus());
                                break;
                            }
                        }
                    }
                    if (StringUtils.isNotBlank(game.getGameResult())) {
                        game.setGameStatus(2);
                    } else {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        Calendar startCalendar = Calendar.getInstance();
                        Date startDate = null;
                        try {
                            startDate = format.parse(game.getDatetime());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        startCalendar.setTime(startDate);
                        startCalendar.add(Calendar.MINUTE, -30);
                        Calendar currentCalendar = Calendar.getInstance();
                        if (currentCalendar.after(startCalendar)) {
                            game.setGameStatus(1);
                        } else {
                            game.setGameStatus(0);
                        }
                    }
                }
            }
            return games;
        }
        return null;
    }

    @Override
    public List<CupBallGame> listPastGames() {
        return cupBallGameMapper.queryPastGames();
    }

    @Override
    public boolean updateStatus(String id) {
        if (StringUtils.isNotBlank(id)) {
            return cupBallGameMapper.updateStatus(id) > 0 ? true : false;
        }
        return true;
    }

    @Override
    public boolean save(CupBallGame game) {
        if (game != null) {
            if (StringUtils.isBlank(game.getId())) {
                game.setId(UF.getRandomUUID());
                game.setAddTime(LocalDateTime.now());
                game.setCode(getGameCode());
                return cupBallGameMapper.insert(game) > 0 ? true : false;
            } else {
                if (StringUtils.isNotBlank(game.getResult())) {
                    String[] infos = StringUtils.split(game.getResult(), COLON);
                    if (infos != null && infos.length == 2) {
                        int num1 = Integer.parseInt(infos[0]);
                        int num2 = Integer.parseInt(infos[1]);
                        if (num1 > num2) {
                            game.setSucceeTeamId(game.getTeamaId());
                        }
                        if (num2 > num1) {
                            game.setSucceeTeamId(game.getTeambId());
                        }
                    }
                }
                game.setModifyTime(LocalDateTime.now());
                return cupBallGameMapper.update(game) > 0 ? true : false;
            }
        }
        return false;
    }

    private String getGameCode() {
        String key = RedisConstantUtil.GAME_CODE_KEY;
        String code = stringRedisTemplate.opsForValue().get(key);
        String channelCode = "";
        if (StringUtils.isBlank(code)) {
            channelCode = String.valueOf(10);
            stringRedisTemplate.opsForValue().set(key, channelCode);
        } else {
            long value = Long.parseLong(code);
            value++;
            channelCode = String.valueOf(value);
            stringRedisTemplate.opsForValue().set(key, channelCode);
        }
        return channelCode;
    }

    @Override
    public CupBallGame getGame(String id) {
        if (StringUtils.isNotBlank(id)) {
            return cupBallGameMapper.findById(id);
        }
        return null;
    }

    @Override
    public List<CupBallGame> query(String startDate, String endDate, int offset, int size) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(startDate)) {
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            params.put("endDate", endDate);
        }
        params.put("offset", offset);
        params.put("size", size);
        return cupBallGameMapper.query(params);
    }

    @Override
    public int count(String startDate, String endDate) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(startDate)) {
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotBlank(endDate)) {
            params.put("endDate", endDate);
        }
        return cupBallGameMapper.count(params);
    }
}
